# Copyright (c) 2025, yuxinyong and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.desk.search import search_widget


class ShoeStyleVariant(Document):
    def onload(self):
        self.auto_fill_complete_shoe_parts()

    def before_print(self, settings=None):
        self.auto_fill_complete_shoe_parts()

    def auto_fill_complete_shoe_parts(self):
        style_doc = frappe.get_doc("Shoe Style", self.style)
        shoe_parts_list = [row for row in style_doc.shoe_parts]
        shoe_part_map ={r.shoe_part: r for r in self.shoe_parts}

        complete_shoe_parts = []
        i = 0
        # override in style variant
        for row in shoe_parts_list:
            i += 1
            if row_override := shoe_part_map.get(row.shoe_part):
                # 不能修改shoe parts里的idx，否则无法正常删除行
                copied_row = row_override.as_dict()
                for field in ('name','parentfield','parenttype'):
                    copied_row.pop(field, None)    #不能复制的字段
                row.update(copied_row)
                row.override_type = "Changed"
            row.idx = i
            self.append("complete_shoe_parts",  row)
        # added from style variant
        style_shoe_part_map ={r.shoe_part: r for r in shoe_parts_list}
        for row in self.shoe_parts:
            if row.shoe_part not in style_shoe_part_map:
                row.override_type = "Added"
                i += 1
                row.idx = i
                self.append("complete_shoe_parts",  row)
            
    def validate(self):
        # empty it as it will be auto loaded 
        self.complete_shoe_parts = []

    def autoname(self):
        """
        style-xx
        """

        last_seq = frappe.db.get_value(self.doctype, 
            {
                "style":self.style
            },
            "seq", order_by="seq desc", for_update=True
        )
        self.seq = last_seq + 1 if last_seq else 1
        self.name = f"{self.style}-{self.seq}"



@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_style_shoe_parts(doctype, txt, searchfield, start, page_len, filters):
    """
    Returns a filtered list of Shoe Part documents based on the parts defined
    in the linked Style document, using the standard search_widget API.
    """

    # We use pop to get the style_name and remove it from the filters
    # as it's not a field on the Shoe Part doctype.
    style_name = filters.pop("style_name", "")

    if not style_name:
        return []

    try:
        style_doc = frappe.get_doc("Shoe Style", style_name)
    except Exception:
        # Return empty list if the Shoe Style document cannot be found.
        return []

    if not style_doc.get("shoe_parts"):
        return []

    # Create a list of the names of the Shoe Parts from the child table.
    allowed_shoe_parts = [d.get("shoe_part") for d in style_doc.get("shoe_parts") if d.get("shoe_part")]

    # Modify the filters to include our custom list of allowed parts.
    new_filters = frappe._dict(filters)
    new_filters["name"] = ("in", allowed_shoe_parts)

    # Call the standard search_widget API with our updated filters.
    # search_widget handles the raw data fetching and filtering, and returns
    # a list of tuples in the format that the client side expects.
    return search_widget(
        doctype=doctype,
        txt=txt,
        searchfield=searchfield,
        start=start,
        page_length=page_len,
        filters=new_filters
    )